package com.JUC.cha03.sec05;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * future的常用方法
 *
 * 2.对计算结果进行处理
 *  2.1.thenApply(v ->{})   计算结果依赖性，线程串行化，当前异常下一步不走
 *  2.2.handle((v,e) ->{})  计算结果依赖性，线程串行化，有异常也可以继续往下走将异常带着进一步处理
 */
public class CompletableFutureAPI2Demo {

    public static void main(String[] args) {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        CompletableFuture.supplyAsync(() ->{
           // 暂停几秒钟线程
           try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println(Thread.currentThread().getName());
            System.out.println("111");
           return 1;
        }, threadPool).handle((f,e) ->{
//            int i = 10/0;
            System.out.println(Thread.currentThread().getName());
            System.out.println("222");
            return f + 2;
        }).handle((f,e) ->{
            System.out.println(Thread.currentThread().getName());
            System.out.println("333");
            return f + 3;
        }).whenComplete((v,e) ->{
            if (e == null){
                System.out.println("----- 程序执行完成 ----- 结果是：" + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "\t" + "先去执行其他任务");
        
        threadPool.shutdown();

    }


}
